import { defineStore } from 'pinia'
import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:8000/api/v1'
})

// 任务状态存储
export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [] as any[],
    currentTask: null as any,
    loading: false,
    error: null as string | null
  }),
  
  actions: {
    // 获取任务列表
    async fetchTasks() {
      this.loading = true
      this.error = null
      try {
        const response = await api.get('/tasks')
        this.tasks = response.data
      } catch (error: any) {
        this.error = error.message || '获取任务列表失败'
        console.error('Failed to fetch tasks:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 创建任务
    async createTask(taskData: any) {
      this.loading = true
      this.error = null
      try {
        const response = await api.post('/tasks/migrate', taskData)
        this.currentTask = response.data
        // 重新获取任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        this.error = error.message || '创建任务失败'
        console.error('Failed to create task:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 创建批量任务
    async createBatchTasks(taskData: any) {
      this.loading = true
      this.error = null
      try {
        // 构造批量任务数据
        const batchTaskData = {
          name: taskData.name,
          source: {
            type: taskData.source.type,
            host: taskData.source.host,
            port: taskData.source.port,
            user: taskData.source.user,
            password: taskData.source.password,
            databases: taskData.source.databases
          },
          target: {
            type: taskData.target.type,
            host: taskData.target.host,
            port: taskData.target.port,
            user: taskData.target.user,
            password: taskData.target.password,
            databases: taskData.target.databases
          },
          options: taskData.options
        }
        
        const response = await api.post('/tasks/migrate/batch', batchTaskData)
        // 重新获取任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        this.error = error.message || '创建批量任务失败'
        console.error('Failed to create batch tasks:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取任务详情
    async fetchTaskDetail(taskId: string) {
      this.loading = true
      this.error = null
      try {
        const response = await api.get(`/tasks/${taskId}`)
        this.currentTask = response.data
        return response.data
      } catch (error: any) {
        this.error = error.message || '获取任务详情失败'
        console.error('Failed to fetch task detail:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 启动任务
    async startTask(taskId: string) {
      this.loading = true
      this.error = null
      try {
        const response = await api.post(`/tasks/${taskId}/start`)
        // 立即更新当前任务状态，避免需要多次点击
        if (this.currentTask && this.currentTask.id == taskId) {
          this.currentTask.status = "RUNNING";
        }
        // 更新任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '启动任务失败'
        this.error = errorMessage
        console.error('Failed to start task:', error)
        throw new Error(errorMessage)
      } finally {
        this.loading = false
      }
    },
    
    // 暂停任务
    async pauseTask(taskId: string) {
      this.loading = true
      this.error = null
      try {
        const response = await api.post(`/tasks/${taskId}/pause`)
        // 更新任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '暂停任务失败'
        this.error = errorMessage
        console.error('Failed to pause task:', error)
        throw new Error(errorMessage)
      } finally {
        this.loading = false
      }
    },
    
    // 恢复任务
    async resumeTask(taskId: string) {
      this.loading = true
      this.error = null
      try {
        const response = await api.post(`/tasks/${taskId}/resume`)
        // 更新任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '恢复任务失败'
        this.error = errorMessage
        console.error('Failed to resume task:', error)
        throw new Error(errorMessage)
      } finally {
        this.loading = false
      }
    },
    
    // 删除任务
    async deleteTask(taskId: string) {
      this.loading = true
      this.error = null
      try {
        const response = await api.delete(`/tasks/${taskId}`)
        // 更新任务列表
        await this.fetchTasks()
        return response.data
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '删除任务失败'
        this.error = errorMessage
        console.error('Failed to delete task:', error)
        throw new Error(errorMessage)
      } finally {
        this.loading = false
      }
    },
    
    // 获取任务状态
    async fetchTaskStatus(taskId: string) {
      try {
        const response = await api.get(`/tasks/${taskId}`)
        return response.data
      } catch (error: any) {
        console.error('Failed to fetch task status:', error)
        throw error
      }
    },
    
    // 测试数据库连接
    async testConnection(connectionConfig: any) {
      try {
        const response = await api.post('/database/test-connection', connectionConfig)
        return response.data
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '连接测试失败'
        console.error('Connection test failed:', error)
        throw new Error(errorMessage)
      }
    },
    
    // 获取数据库列表
    async getDatabases(connectionConfig: any) {
      try {
        const response = await api.post('/database/list-databases', connectionConfig)
        return response.data.databases
      } catch (error: any) {
        const errorMessage = error.response?.data?.detail || error.message || '获取数据库列表失败'
        console.error('Failed to get databases:', error)
        throw new Error(errorMessage)
      }
    }
  }
})